<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="video-detail-head">
    <CommonHead title="视频详情"/>
  </header>

  <!--体: 引入FreeVideo子组件，展示视频基础信息，展示标签页和对应的子组件-->
  <section class="video-detail-body">

    <!--引入FreeVideo子组件-->
    <FreeVideo :firstEpisodeUrl="firstEpisodeUrl"/>

    <!--展示视频信息: 视频标题，视频评分，视频作者，创建日期，更新日期，折后价格，视频简介-->
    <van-cell-group>
      <van-cell icon="notes-o" title="视频标题" :value="video['videoTitle']"/>
      <van-cell icon="star-o" title="视频评分">
        <van-rate v-model="video['star']"/>
      </van-cell>
      <van-cell icon="user-o" title="视频作者" :value="video['author']"/>
      <van-cell icon="clock-o" title="创建日期" :value="toDateStr(video['createTime'])"/>
      <van-cell icon="clock-o" title="更新日期" :value="toDateStr(video['modifyTime'])"/>
      <van-cell icon="cash-o" title="折后价格" :value="video['price'] + ' 元'"/>
      <van-cell icon="font-o" title="视频简介" :value="video['videoInfo']===''?'该视频暂无描述':video['videoInfo']"/>
    </van-cell-group>

    <!--标签页: 卡片风格，黑底，橙字，双绑currentTabName，点击时触发-->
    <article class="tabs">
      <van-tabs type="card" v-model:active="currentTabName" @click-tab="changeTab">
        <van-tab title="摘要" name="摘要"></van-tab>
        <van-tab title="目录" name="目录"></van-tab>
      </van-tabs>
    </article>

    <!--选项卡对应要显示的组件: 属性 `:is` 的值是哪个组件的名称，就显示哪个组件-->
    <component :is="currentTabComponent"
               :summaryImage="video['summaryImage']"
               :chapters="video['chapters']"/>
  </section>

  <!--脚: 加入购物车按钮-->
  <footer class="video-detail-foot">
    <van-submit-bar button-text="加入购物车" @submit="addToCart"/>
  </footer>

</template>

<script setup>
import CommonHead from '@/components/CommonHead';
import FreeVideo from '@/views/home/FreeVideo';
import {SELECT_BY_VIDEO_ID} from '@/api/video';
import {onMounted, shallowRef} from "vue";
import router from '@/router';
import {showFailToast} from "vant";
import {SUCCESS, toDateStr} from "@/constant";
import TabSummary from '@/views/home/TabSummary';
import TabCatalog from '@/views/home/TabCatalog';
import {INSERT} from '@/api/cart';
import {useStore} from "vuex";

/* ==================== data ==================== */

// data: 从当前路由中获取视频主键
const videoId = router.currentRoute.value.query['videoId'];
// data: 视频对象
let video = shallowRef({});
// data: 视频第一集的URL地址
let firstEpisodeUrl = shallowRef('');
// data: 当前选项卡的name值，初始为 "摘要"
let currentTabName = shallowRef('摘要');
// data: 当前选项卡展示的子组件，初始为TabSummary摘要子组件
let currentTabComponent = shallowRef(TabSummary);
// data: Vuex实例，直接使用useStore()会报错
const vuex = useStore();

/* ==================== method ==================== */

// method: 查询视频详情
async function searchByVideoId(videoId) {
  // 异步调用根据视频主键查询视频详情的接口
  let result = await SELECT_BY_VIDEO_ID(videoId);
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    let data = resp.data;
    video.value = data;
    // 如该视频存在章集记录，则赋值视频第一集的URL地址
    if (null !== data['chapters'] && data['chapters'].length > 0) {
      let episodes = data['chapters'][0]['episodes'];
      if (null != episodes && episodes.length > 0) {
        firstEpisodeUrl.value = episodes[0]['episodeUrl'];
      }
    }
  } else showFailToast(resp.message + ': ' + resp.data);
}

// method: 当切换选项卡时触发
function changeTab(tab) {
  currentTabComponent.value = tab.name === '摘要' ? TabSummary : TabCatalog;
}

// method: 将视频添加到购物车
async function addToCart() {

  // 未登录保护: 1秒之后跳入 LoginByAccount 组件
  if (!vuex.state['loginFlag']) {
    showFailToast('请先登录');
    setTimeout(() => router.push("/LoginByAccount"), 1000);
    return;
  }

  // 准备请求参数
  let param = {
    'videoId': videoId,
    'videoTitle': video.value['videoTitle'],
    'price': video.value['price'],
    'author': video.value['author'],
    'coverImage': video.value['coverImage']
  }

  // 异步添加购物车记录
  const result = await INSERT(param);
  let resp = result['data'];

  // 若添加成功，则跳入Cart组件
  if (resp.code === SUCCESS) {
    await router.push('/Cart');
  } else showFailToast(resp.message + ': ' + resp.data);
}

/* ==================== mounted ==================== */

// mounted: DOM挂载后，查询视频详情
onMounted(() => searchByVideoId(videoId));
</script>

<style scoped lang="scss">
.video-detail-body {
  margin-bottom: 50px; // 下外边距

  /*选项卡区域*/
  .tabs {
    margin: 15px 0; // 上下外边距，左右自动
  }
}
</style>